package com.wjyf.reducing_bento.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.wjyf.reducing_bento.common.ErrorCode;
import com.wjyf.reducing_bento.model.entity.CouponBean;
import com.wjyf.reducing_bento.model.entity.CouponReceiveBean;
import com.wjyf.reducing_bento.model.entity.UserBean;
import com.wjyf.reducing_bento.exception.BusinessException;
import com.wjyf.reducing_bento.mapper.CouponReceiveMapper;
import com.wjyf.reducing_bento.service.CouponReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wjyf.reducing_bento.service.CouponService;
import com.wjyf.reducing_bento.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.wjyf.reducing_bento.constant.CouponConstant.HOLDING;
import static com.wjyf.reducing_bento.constant.CouponReceiveConstant.NOT_USED;

/**
 * <p>
 * 优惠券领取记录表 服务实现类
 * </p>
 *
 * @author wjyf
 * @since 2023-03-14 08:36:33
 */
@Service
public class CouponReceiveServiceImpl extends ServiceImpl<CouponReceiveMapper, CouponReceiveBean> implements CouponReceiveService {

    @Resource
    private UserService userService;

    @Resource
    private CouponService couponService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean receive(Integer couponId, HttpServletRequest request) {
        if (couponId == null || couponId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //查询优惠卷
        CouponBean couponBean = couponService.getById(couponId);
        if (couponBean == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该优惠卷不存在");
        }
        if (couponBean.getStatus() != HOLDING){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "该优惠卷已经过期或未开始");
        }
        String couponIdString = String.valueOf(couponId);
        UserBean user = userService.getUser(request);
        // 优惠卷只能领取一次
        List<CouponReceiveBean> couponReceiveBeanList = list(new LambdaQueryWrapper<CouponReceiveBean>()
                .eq(CouponReceiveBean::getCouponId, couponId)
                .eq(CouponReceiveBean::getUId, user.getUId())
        );
        List<CouponReceiveBean> notUsedCouponReceive = couponReceiveBeanList.stream().filter(couponReceiveBean -> couponReceiveBean.getStatus() == NOT_USED).collect(Collectors.toList());
        if (ObjectUtils.isNotEmpty(notUsedCouponReceive)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "该优惠卷已经领取过啦~不能重复领取哦");
        }
        synchronized (this) {
            CouponReceiveBean couponReceiveBean = new CouponReceiveBean();
            couponReceiveBean.setUId(user.getUId())
                    .setCouponId(couponBean.getId())
                    .setCouponMoney(couponBean.getMoney())
                    .setCreateTime(new Date())
                    .setFullMoney(couponBean.getFullMoney())
                    .setStatus(NOT_USED);
            couponBean.setCpnum(couponBean.getCpnum() - 1);
            boolean save = save(couponReceiveBean);
            boolean update = couponService.updateById(couponBean);
            if (!save || !update) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
        }
        return true;
    }
}
